// pages/danger/selfAdd/index.js
import Dialog from '../../../dist/dialog/dialog.js';
import Toast from '../../../dist/toast/toast.js';
var app = getApp()
var util = require('../../../utils/util.js')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    baseUrl: app.globalData.baseUrl,


    inspectId: 0,
    inspectList: [],
    title: '检查表标题',
    head: ['序号', '检查项目', '检查内容', '操作'],
    hiddenModal: true,
    inspectPublicId: 0,
    processInstanceId: "",
    taskId: "",
    dangerLevelOptions: ['一般(C级)', '一般(B级)', '重大(A级)'],


    selectLevel: "一般（C级）",
    inspectListPublic: {},
    inspectListPublicIndex: 0, //当前编辑的检查项目在inspectList中的index
    deadline: "",
    inspectResult: "", //检查记录
    needChange: false,
    tempImagePaths: [],
    inspectImageIds: [],
    reformImagePaths: [],
    reformImageIds: [],
    changeExplain: "", //整改说明

    //工作流相关参数
    taskId: "", //任务id    
    reform: true,
    check: true,
    inspectType: 0, //隐患检查单类型
    //整改单的相关参数
    reformSheetId: 0,
    reformReply: "", //整改回执

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var that = this
    this.setData({
      inspectId: options.inspectId,
      taskId: options.taskId,
      title: options.inspectName,
      inspectType: options.inspectType
    })

    that.loadInspectPublicDetail(options.inspectId);
    that.loadReformSheet()
  },
  //提交当前任务
  doTask(e) {
    var that = this
    Dialog.confirm({
      title: '提示',
      message: '是否提交整改单',
      selector: '#van-dialog-doTask',

    }).then(() => {
      var header;

      header = {
        'Cookie': wx.getStorageSync("sessionid"), //读取cookie
        'content-type': 'application/x-www-form-urlencoded'
      };
      var params = {
        taskId: that.data.taskId,
        reform: true,
        type: parseInt(that.data.inspectType)
      }
      if (that.data.inspectType == 0) {
        params.reform = false
      } else {
        params.check = false
      }
      that.saveReformSheet()
      wx.request({
        url: app.globalData.baseUrl + '/safe/dangerFlow/doTask',
        header: header,
        method: "POST",
        data: params,
        success(res) {
          wx.navigateBack({
            delta: 1
          })
        }
      })
    }).catch(() => {

    });

  },
  //加载整改单的信息
  loadReformSheet() {
    var that = this
    var header;
    var user = app.globalData.user
    header = {
      'Cookie': wx.getStorageSync("sessionid"), //读取cookie
      'content-type': 'application/x-www-form-urlencoded'
    };
    wx.request({
      url: app.globalData.baseUrl + '/safe/danger/reformSheet/find?dangerInspectPublicId=' +
        that.data.inspectId + '&applyUserId=' + user.userId,
      header: header,
      method: "GET",
      success(res) {
        if (res.data.success && res.data.data.length > 0) {
          var reformSheet = res.data.data[0]
          var reformReply = ''
          if (res.data.data[0].reformReply) {
            reformReply = res.data.data[0].reformReply
          } else {
            reformReply="所列整改项目，已于" + util.formatTime(new Date) + "整改完毕，请验收。"
          }
          that.setData({
            reformSheetId: reformSheet.id,
            reformReply: reformReply
          })
        }
      }
    })
  },


  /**
   * 加载发布的隐患排查的检查单
   */
  loadInspectPublicDetail(inspectPublicId) {

    var that = this
    var header;
    that.setData({
      inspectPublicId: inspectPublicId
    })
    header = {
      'Cookie': wx.getStorageSync("sessionid") //读取cookie
    };
    wx.request({
      url: app.globalData.baseUrl + '/safe/danger/inspectListPublic/find',
      header: header,
      method: "POST",
      data: {
        inspectPublicId: inspectPublicId,
        applyUserId: app.globalData.user.id,
        needChange: 1
      },
      success(res) {
        var inspectList = res.data.data
        for (var i = 0; i < inspectList.length; i++) {
          if (inspectList[i].deadline) {
            inspectList[i].deadlineStr = util.formatTime(new Date(inspectList[i].deadline))
          } else {
            inspectList[i].deadlineStr = "无"
          }
          if (!inspectList[i].hiddenDangerLevel) {
            inspectList[i].hiddenDangerLevel = "无"
          }
        }
        that.setData({
          inspectList: inspectList,
        })
      }
    })
  },
  //保存整改单信息
  saveReformSheet() {
    var that = this
    var header;

    header = {
      'Cookie': wx.getStorageSync("sessionid") //读取cookie
    };
    var params = {
      dangerInspectPublicId: parseInt(that.data.inspectId),
      reformReply: that.data.reformReply,
      id: that.data.reformSheetId
    }

    wx.request({
      url: app.globalData.baseUrl + '/safe/danger/reformSheet/update',
      header: header,
      method: "GET",
      data: params,
      success(res) {
        wx.navigateBack({
          delta: 1
        })
      }
    })
  },
  /**
   * 显示记录隐患的窗口
   */
  showInspectModal(e) {
    var index = e.currentTarget.dataset.index
    var inspectPublicListId = e.currentTarget.dataset.inpsectpubliclistid
    var inspectPublicList = this.data.inspectList[index]
    this.setData({
      hiddenModal: false,
      changeExplain: inspectPublicList.changeExplain
    })
    this.setData({
      inspectListPublic: inspectPublicList,
      inspectListPublicIndex: index
    })
    this.initInspectListPublic(inspectPublicList)
  },
  /**
   * 点击记录，加载隐患记录的信息
   */
  initInspectListPublic(inspectPublicList) {
    var needChange = false;
    if (inspectPublicList.needChange == 0) {
      needChange = false
    } else {
      needChange = true
    }
    var deadline = ''
    if (inspectPublicList.deadline) {
      deadline = util.formatTime(new Date(inspectPublicList.deadline), 'Y/M/D')

    } else {
      deadline = util.formatTime(new Date())
    }
    let dangerPicList=[];
    inspectPublicList.dangerPics.forEach(function (item) {
        dangerPicList.push({
            fId:item.fId,
            url:app.globalData.fileUrl+item.path+'?x-oss-process=image/resize,m_fixed,h_70,w_70',
            oriUrl:app.globalData.fileUrl+item.path
        })
    });
    let changePicList=[];
      inspectPublicList.changePics.forEach(function (item) {
          changePicList.push({
            fId:item.fId,
            url:app.globalData.fileUrl+item.path+'?x-oss-process=image/resize,m_fixed,h_70,w_70',
            oriUrl:app.globalData.fileUrl+item.path
        })
    });
    this.setData({
      inspectResult: inspectPublicList.inspectResult,
      deadline: deadline,
      selectLevel: '一般(C级)',
      needChange: needChange,
      tempImagePaths: dangerPicList,
      reformImagePaths: changePicList,
    })
    if (inspectPublicList.hiddenDangerLevel) {
      this.setData({
        selectLevel: inspectPublicList.hiddenDangerLevel,
      })
    }
  },

  /**
   * 选择隐患照片
   */
  chooseInspectImage() {
    var that = this
    if (this.data.reformImagePaths.length >= 3) {
      wx.showToast({
        title: '整改图片最多添加3张',
        icon: 'none',
      })
      return
    }
    wx.chooseImage({
      count: 1,
      success: function(res) {
          if (res.tempFilePaths.length > 0) {
              let tempFile=res.tempFilePaths[0];
              wx.request({
                  url: app.globalData.baseUrl + '/safe/sys/oss/sign',
                  method: 'get',
                  data: { contentId: that.data.inspectListPublic.id, contentType:6},//隐患排查的整改照片
                  success(res) {
                      wx.uploadFile({
                          url: app.globalData.fileUrl,
                          filePath: tempFile,
                          name: 'file',
                          formData: {
                              name:tempFile,
                              key:res.data.dir + tempFile,
                              policy:res.data.policy,
                              OSSAccessKeyId:res.data.accessid,
                              success_action_status:'200',
                              signature:res.data.signature,
                              callback:res.data.callback
                          },
                          success: function (res) {
                              let resultJson=JSON.parse(res.data);
                              let decodeDataJson=util.decode(resultJson.file);
                              let newPicList=that.data.reformImagePaths;
                              //修改显示图片列表
                              newPicList.push({
                                  fId:decodeDataJson.fId,
                                  url:app.globalData.fileUrl+decodeDataJson.path+'?x-oss-process=image/resize,m_fixed,h_70,w_70',
                                  oriUrl:app.globalData.fileUrl+decodeDataJson.path
                              });
                              //修改全体数据
                              var dangerInspectLstPublic = that.data.inspectList[that.data.inspectListPublicIndex]
                              dangerInspectLstPublic.changePics.push({fId:decodeDataJson.fId, path:decodeDataJson.path})
                              var inspectList = that.data.inspectList
                              inspectList[that.data.inspectListPublicIndex] = dangerInspectLstPublic
                              that.setData({
                                  reformImagePaths:newPicList,
                                  inspectList: inspectList
                              })
                          }
                      })

                  }
              })

          }
      },
    })
  },

  /**
   * 删除上传的隐患照片
   */
  deleteInspectImage(e) {
    var imageIndex = e.currentTarget.dataset.index
    var that = this
    Dialog.confirm({
      title: '删除照片',
      message: '确认删除隐患照片'
    }).then(() => {
      var header = {
        'Cookie': wx.getStorageSync("sessionid") //读取cookie
      };
      var fId = that.data.reformImagePaths[imageIndex].fId
      wx.request({
        url: app.globalData.baseUrl + '/safe/file/delete?fId=' + fId,
        header: header,
        method: "GET",
        success(res) {
          if (res.data.success) {
            // Toast('删除照片成功');
            var reformImagePaths = that.data.reformImagePaths
            reformImagePaths.splice(imageIndex, 1)
            that.setData({
              reformImagePaths: reformImagePaths
            })
            //更新隐患检查单中的隐患照片信息
            var dangerInspectLstPublic = that.data.inspectList[that.data.inspectListPublicIndex]
            dangerInspectLstPublic.changePics.splice(imageIndex, 1)
            var inspectList = that.data.inspectList
            inspectList[that.data.inspectListPublicIndex] = dangerInspectLstPublic
            that.setData({
              inspectList: inspectList,
              inspectListPublic: dangerInspectLstPublic
            })
            that.hiddenModal = true
          } else {
            // Toast('删除照片失败，可能网络错误或者网页端已删除');
          }
        }
      })

    }).catch(() => {

    })
  },
  /**
   * 预览隐患照片
   */
  previewDangerImage(e) {
    var src = e.currentTarget.dataset.src;
    var imageList = new Array();
    for (var i = 0; i < this.data.tempImagePaths.length; i++) {
        imageList.push(this.data.tempImagePaths[i].oriUrl)
    }
    wx.previewImage({
      current: src,
      urls: imageList,
    })
  },
    /**
     * 预览整改照片照片
     */
    previewChangeImage(e){
        var src = e.currentTarget.dataset.src;
        var imageList = new Array();
        for (var i = 0; i < this.data.reformImagePaths.length; i++) {
            imageList.push(this.data.reformImagePaths[i].oriUrl)
        }
        wx.previewImage({
            current: src,
            urls: imageList,
        })
    },
  /**
   * 隐藏窗口
   */
  hiddenInspectModal() {
    this.setData({
      hiddenModal: true
    })
  },

  /**
   * 保存单个隐患检查记录
   */
  saveInspectList() {
    var that = this
    var inspectNeedChange = 0;
    if (this.data.needChange) {
      inspectNeedChange = 1;
    }
    var header = {
      'Cookie': wx.getStorageSync("sessionid") //读取cookie
    };
    var params = {
      changeTime: new Date(),
      changeExplain: this.data.changeExplain,
      id: this.data.inspectListPublic.id,
    }
    wx.request({
      url: app.globalData.baseUrl + '/safe/danger/inspectListPublic/update',
      header: header,
      method: "POST",
      data: params,
      success(res) {
        if (res.data.success) {
          var param = "inspectList[" + that.data.inspectListPublicIndex + "]"
          var inspectListPublic = that.data.inspectList[that.data.inspectListPublicIndex]
          inspectListPublic.inspectResult = that.data.inspectResult
          inspectListPublic.deadlineStr = util.formatTime(new Date(that.data.deadline))
          var inspectList = that.data.inspectList
          inspectList[that.data.inspectListPublicIndex] = inspectListPublic
          that.setData({
            inspectList: inspectList,
            hiddenModal: true
          })
        }
      }
    })

  },
  /**
   * 将隐患检查记录的结果暂存到data中去
   */
  bindInspectResultBlur(e) {
    this.setData({
      inspectResult: e.detail.value
    })
  },

  /**
   * 将隐患整改说明绑定
   */
  bindChangeExplain(e) {
    this.setData({
      changeExplain: e.detail
    })
  },
  bindReformReply(e) {
    this.setData({
      reformReply: e.detail
    })
  },



  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})